use-shallow-routing.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { useEffect, useRef } from 'react';
  2. import { isClient } from '@growi/core/dist/utils';
  3. import { useRouter } from 'next/router';
  4. import type { Props } from '../general-page/types';
  5. /**
  6. * Custom hook for syncing pathname by Shallow Routing
  7. * Optimized to minimize unnecessary router operations and re-renders
  8. */
  9. export const useShallowRouting = (props: Props): void => {
  10. const router = useRouter();
  11. const lastPathnameRef = useRef<string>();
  12. // Sync pathname by Shallow Routing with performance optimization
  13. useEffect(() => {
  14. if (!isClient() || !props.currentPathname) return;
  15. // Skip if pathname hasn't changed (prevents unnecessary operations)
  16. if (lastPathnameRef.current === props.currentPathname) return;
  17. const currentURL = decodeURI(window.location.pathname);
  18. // Only update if URLs actually differ
  19. if (currentURL !== props.currentPathname) {
  20. const { search, hash } = window.location;
  21. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  22. }
  23. // Update reference for next comparison
  24. lastPathnameRef.current = props.currentPathname;
  25. }, [props.currentPathname, router]);
  26. };